package com.psy.counseling.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.psy.counseling.entity.Question;
import com.psy.counseling.entity.Test;
import com.psy.counseling.entity.TestQuestion;
import com.psy.counseling.mapper.TestMapper;
import com.psy.counseling.service.QuestionService;
import com.psy.counseling.service.TestService;
import com.psy.counseling.service.UserService;
import com.psy.counseling.utils.Result;
import com.psy.counseling.vo.TestVO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.psy.counseling.entity.User;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  套题的增删改查
 * </p>
 *
 * @author 陈灿
 * @since 2022-05-31
 */

@RestController
@RequestMapping("/api/test")
public class TestController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final String KEY = "question_recommend";
    @Resource
    private TestService testService;
    @Resource
    private TestMapper testMapper;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UserService userService;
    @Resource
    private QuestionService questionService;
    public User getUser() {
        String token = request.getHeader("token");
        String username = JWT.decode(token).getAudience().get(0);
        return userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
    }


    /*    @GetMapping("/score")
        public Result<?> sumScore(@RequestBody Test test){

        }*/
    @PostMapping("/addQuestion")
    public Result<?> addQuestion(@RequestBody TestQuestion que) {
        System.out.println(que.getTestId());
        try {
            testService.insertQue(que);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.success(false);
        }
        return Result.success(true);
    }
    /*    @PostMapping("/addSong")
        public Result<?> addSong(@RequestBody SongSheetRel rel) {
            try {
                songSheetService.insertRel(rel);
                // 删除缓存
                stringRedisTemplate.delete(KEY);
            } catch (Exception e) {
                return Result.success(false);
            }
            return Result.success(true);
        }*/
    @GetMapping("/question/{id}")
    public Result<?> song(@PathVariable Integer id) {
        List<Question> list = new ArrayList<>();
        List<TestQuestion> tests = testMapper.getRelBySheetId(id);
        for (TestQuestion test : tests) {
            Integer queId = test.getQueId();
            Question question = questionService.getById(queId);
            list.add(question);
        }
        return Result.success(list);
    }
    /*    @GetMapping("/song/{id}")
        public Result<?> song(@PathVariable Integer id) {
            List<Song> list = new ArrayList<>();
            List<SongSheetRel> songSheets = songSheetMapper.getRelBySheetId(id);
            for (SongSheetRel songSheet : songSheets) {
                Integer songId = songSheet.getSongId();
                Song song = songService.getById(songId);
                list.add(song);
            }
            return Result.success(list);
        }*/
    @PostMapping
    public Result<?> save(@RequestBody Test test) {
        testService.save(test);
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody Test test) {
        testService.updateById(test);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        testService.removeById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> findById(@PathVariable Long id) {
        Test tests = testService.getById(id);
        List<Question> list = new ArrayList<>();
        List<TestQuestion> rels = testMapper.getRelBySheetId(tests.getId());
        for (TestQuestion test : rels) {
            Integer questionId = test.getQueId();
            Question question = questionService.getById(questionId);
            list.add(question);
        }
        tests.setQuestions(list);
        return Result.success(tests);
    }
/*    @GetMapping("/{id}")
    public Result<?> findById(@PathVariable Long id) {
        SongSheet sheet = songSheetService.getById(id);
        List<Song> list = new ArrayList<>();
        List<SongSheetRel> rels = songSheetMapper.getRelBySheetId(sheet.getId());
        for (SongSheetRel songSheet : rels) {
            Integer songId = songSheet.getSongId();
            Song song = songService.getById(songId);
            list.add(song);
        }
        sheet.setSongs(list);
        return Result.success(sheet);
    }*/

    @GetMapping
    public Result<?> findAll() {
        List<TestVO> list = testService.lists();
        return Result.success(list);
    }

    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(required = false, defaultValue = "") String name,
                              @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                              @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<Test> query = Wrappers.<Test>lambdaQuery().orderByDesc(Test::getId);
        if (StrUtil.isNotBlank(name)) {
            query.like(Test::getTestName, name);
        }
        IPage<Test> page = testService.page(new Page<>(pageNum, pageSize), query);
        return Result.success(page);
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {

        List<Map<String, Object>> list = CollUtil.newArrayList();

        List<Test> all = testService.list();
        for (Test obj : all) {
            Map<String, Object> row = new LinkedHashMap<>();
            row.put("id", obj.getId());
            row.put("测验编号", obj.getTestName());
            row.put("测验类型", obj.getTypId());


            list.add(row);
        }

        // 2. 写excel
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("测验信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(System.out);
    }

    @GetMapping("/upload/{fileId}")
    public Result<?> upload(@PathVariable String fileId) {
        String basePath = System.getProperty("user.dir") + "/src/main/resources/static/file/";
        List<String> fileNames = FileUtil.listFileNames(basePath);
        String file = fileNames.stream().filter(name -> name.contains(fileId)).findAny().orElse("");
        List<List<Object>> lists = ExcelUtil.getReader(basePath + file).read(1);
        List<Test> saveList = new ArrayList<>();
        for (List<Object> row : lists) {
            Test obj = new Test();
            obj.setTestName((String) row.get(1));
            obj.setTypId((String) row.get(2));

            saveList.add(obj);
        }
        testService.saveBatch(saveList);
        return Result.success();
    }
}
